package com.dxb.test.lang;

import org.testng.annotations.Test;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * ClassName：com.dxb.test.lang.IntegerPrint <br>
 * Description：TODO <br>
 *
 * @author 戴晓波 <br>
 * Date 2022/2/16/016 9:09 <br>
 * @version v1.0 <br>
 */
public class IntegerPrint {
    /**
     * 打印二进制
     */
    @Test
    public void printIntegerBinary() {
        int a = 1;
        int b = -1;
        System.out.println(Integer.toBinaryString(a));
        System.out.println(Integer.toBinaryString(b));
    }

    /**
     * 16进制转10进制
     */
    @Test
    public void print16to10() {
        String target = "1AF";
        System.out.println(new BigInteger(target, 16));

        BigInteger result = new BigInteger("0");
        for (int i = 0; i < target.length(); i++) {
            char c = target.charAt(target.length() - 1 - i);
            BigInteger cInt = null;
            if (c >= 'A' && c <= 'F') {
                cInt = new BigInteger(String.valueOf(c - 'A' + 10));
            } else {
                cInt = new BigInteger(String.valueOf(c));
            }
            cInt = new BigInteger("16").pow(i).multiply(cInt);
            result = result.add(cInt);
        }
        System.out.println(result);
    }

    /**
     * 观察BigInteger初始化过程
     */
    @Test
    public void debugBigInteger() {
        BigInteger big = new BigInteger("123456789987654321123456789987654321123456789987654321");
        big.toString();
    }

    /**
     * BigDecimal
     */
    @Test
    public void debugBigDecimal() {
        BigDecimal bigDecimal = new BigDecimal(1);
        BigDecimal bigDecimal1 = new BigDecimal(1);
        System.out.println(bigDecimal.equals(bigDecimal1));

        BigDecimal bigDecimal2 = new BigDecimal(1);
        BigDecimal bigDecimal3 = new BigDecimal(1.0);
        System.out.println(bigDecimal2.equals(bigDecimal3));

        BigDecimal bigDecimal4 = new BigDecimal("1");
        BigDecimal bigDecimal5 = new BigDecimal("1.00");
        System.out.println(bigDecimal4.equals(bigDecimal5));

        System.out.println(bigDecimal4.compareTo(bigDecimal5) == 0);
        //标度不一样
        printBigDecimal(new BigDecimal(0.1));
        printBigDecimal(BigDecimal.valueOf(0.1));
        //超级大数呢
        BigDecimal big = new BigDecimal("123456789987654321123456789987654321123456789987654321.1");
        printBigDecimal(big);
    }

    private void printBigDecimal(BigDecimal big) {
        String[] fields = {"intVal", "scale", "intCompact", "precision"};
        StringBuilder sb = new StringBuilder();
        try {
            for (String fieldStr : fields) {

                Field field = big.getClass().getDeclaredField(fieldStr);
                field.setAccessible(true);
                sb.append(fieldStr).append(":").append(field.get(big)).append(";");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sb);
    }
}
